import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.xtoneict.framework.expands.http.api.HttpRequest;
import com.xtoneict.framework.expands.http.okhttpclient.SimpleHttpRequest;
import com.xtoneict.framework.expands.http.okhttpclient.SimpleRequestBuilder;
import com.xtoneict.framework.util.json.JsonUtils;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.poi.ss.usermodel.Workbook;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;
import java.util.zip.GZIPInputStream;

/**
 * <pre>
 * @TODO 添加文件描述
 * </pre>
 *
 * @author jew
 * @date 2022/3/22 16:01
 * @company 成都信通信息技术有限公司
 */
public class SearchJob {

    public static void main(String[] args) {
        //String companyStr = "[{\"id\":\"3124522445\",\"name\":\"四川发展新兴产业园区投资建设管理有限责任公司\"},{\"id\":\"160440319\",\"name\":\"四川产业振兴发展投资基金有限公司\"},{\"id\":\"2344519103\",\"name\":\"四川发展产业引导股权投资基金管理有限责任公司\"},{\"id\":\"3407720029\",\"name\":\"四川省先进材料产业投资集团有限公司\"},{\"id\":\"3465460296\",\"name\":\"四川文化产业投资集团有限责任公司\"},{\"id\":\"4833075787\",\"name\":\"蜀道投资集团有限责任公司\"},{\"id\":\"3464803166\",\"name\":\"四川新华出版发行集团有限公司\"},{\"id\":\"3445732582\",\"name\":\"四川发展兴瑞投资有限责任公司\"},{\"id\":\"3270805884\",\"name\":\"四川发展引领资本管理有限公司\"},{\"id\":\"146444322\",\"name\":\"四川航空集团有限责任公司\"},{\"id\":\"160440301\",\"name\":\"四川省有色科技集团有限责任公司\"},{\"id\":\"144176220\",\"name\":\"四川省铁路产业投资集团有限责任公司\"},{\"id\":\"3372444303\",\"name\":\"四川生物医药产业集团有限责任公司\"},{\"id\":\"945093425\",\"name\":\"四川省城乡建设投资有限责任公司\"},{\"id\":\"3409102535\",\"name\":\"四川天府健康产业投资集团有限责任公司\"},{\"id\":\"149266301\",\"name\":\"四川省盐业总公司\"},{\"id\":\"2350703706\",\"name\":\"四川省水务投资集团有限责任公司\"},{\"id\":\"160511989\",\"name\":\"四川省人民政府金牛宾馆\"},{\"id\":\"185227386\",\"name\":\"四川省交通投资集团有限责任公司\"},{\"id\":\"3270055818\",\"name\":\"四川发展大数据产业投资有限责任公司\"},{\"id\":\"5009655295\",\"name\":\"四川发展航空产业投资集团有限公司\"},{\"id\":\"155190314\",\"name\":\"四川省国有资产经营投资管理有限责任公司\"},{\"id\":\"3362355078\",\"name\":\"四川发展城市建设投资有限责任公司\"},{\"id\":\"316785845\",\"name\":\"四川省能源投资集团有限责任公司\"},{\"id\":\"3276937143\",\"name\":\"北京川发投资管理有限公司\"},{\"id\":\"4337527574\",\"name\":\"四川发展资产经营投资管理有限公司\"},{\"id\":\"3346958112\",\"name\":\"四川发展轨道交通产业投资有限公司\"},{\"id\":\"357496250\",\"name\":\"四川省矿业投资集团有限责任公司\"},{\"id\":\"5325580679\",\"name\":\"四川林业集团有限公司\"},{\"id\":\"146867917\",\"name\":\"四川省国有资产投资管理有限责任公司\"},{\"id\":\"3474939974\",\"name\":\"四川企业改革发展股权投资基金合伙企业（有限合伙）\"},{\"id\":\"2667539777\",\"name\":\"四川融创助业投资发展有限公司\"},{\"id\":\"3379547339\",\"name\":\"四川省生态环保产业集团有限责任公司\"},{\"id\":\"3091251344\",\"name\":\"四川发展国惠小额贷款有限公司\"},{\"id\":\"3000581204\",\"name\":\"四川天府弘威军民融合产业发展股权投资基金合伙企业（有限合伙）\"},{\"id\":\"4282666166\",\"name\":\"四川发展甲乙丙资产重组投资有限公司\"},{\"id\":\"2311205694\",\"name\":\"四川宇晟酒业投资管理有限公司\"},{\"id\":\"18440741\",\"name\":\"西南联合产权交易所有限责任公司\"},{\"id\":\"2311848904\",\"name\":\"四川晟天新能源发展有限公司\"},{\"id\":\"3292330364\",\"name\":\"四川众铸政府与社会资本股权投资基金合伙企业（有限合伙）\"},{\"id\":\"168263536\",\"name\":\"四川科能锂电有限公司\"},{\"id\":\"81430135\",\"name\":\"四川发展土地资产运营管理有限公司\"},{\"id\":\"3431285953\",\"name\":\"四川蜀兴智行管理咨询有限责任公司\"},{\"id\":\"1512308906\",\"name\":\"四川水务环保股权投资中心（有限合伙）\"},{\"id\":\"352446181\",\"name\":\"国药四川医药集团有限公司\"},{\"id\":\"2990223594\",\"name\":\"四川金融控股集团有限公司\"},{\"id\":\"1674024998\",\"name\":\"四川发展文化旅游股权投资基金合伙企业（有限合伙）\"},{\"id\":\"2993160451\",\"name\":\"四川中小企业发展股权投资基金合伙企业（有限合伙）\"},{\"id\":\"320239496\",\"name\":\"四川九强通信科技有限公司\"},{\"id\":\"293613965\",\"name\":\"润和催化剂股份有限公司\"},{\"id\":\"3469454897\",\"name\":\"天府信用增进股份有限公司\"},{\"id\":\"3111833690\",\"name\":\"四川省兴文石海天下奇文化旅游投资有限责任公司\"},{\"id\":\"3167133596\",\"name\":\"四川欧亚路态贸易股份有限公司\"},{\"id\":\"2352027804\",\"name\":\"四川旅游产业创新发展股权投资基金中心（有限合伙）\"},{\"id\":\"3172839639\",\"name\":\"国宝人寿保险股份有限公司\"},{\"id\":\"1291959468\",\"name\":\"四川海特航空创业投资基金合伙企业（有限合伙）\"},{\"id\":\"4292054195\",\"name\":\"四川发展创融企业管理合伙企业（有限合伙）\"},{\"id\":\"167901434\",\"name\":\"成都芝田高分子材料有限公司\"},{\"id\":\"308179763\",\"name\":\"四川省机场集团有限公司\"},{\"id\":\"1692194441\",\"name\":\"北川安特天然药业有限公司\"},{\"id\":\"174474941\",\"name\":\"宜宾盈泰光电有限公司\"},{\"id\":\"373217154\",\"name\":\"成都双流国际机场股份有限公司\"},{\"id\":\"2351674713\",\"name\":\"成都中弘节能环保科技有限公司\"},{\"id\":\"3386621968\",\"name\":\"四川创兴先进制造业投资有限公司\"},{\"id\":\"199515953\",\"name\":\"成都市新筑路桥机械股份有限公司\"},{\"id\":\"2358930916\",\"name\":\"四川发展兴川产业引导股权投资基金合伙企业（有限合伙）\"},{\"id\":\"3032049854\",\"name\":\"四川省旅游投资集团有限责任公司\"},{\"id\":\"413669211\",\"name\":\"四川科芯照明股份有限公司\"},{\"id\":\"293323408\",\"name\":\"成都新橙北斗智联有限公司\"},{\"id\":\"2388265472\",\"name\":\"四川众建政府与社会资本股权投资基金合伙企业（有限合伙）\"},{\"id\":\"848026964\",\"name\":\"乐山市沙湾区嘉胜国有资产经营投资有限公司\"},{\"id\":\"261834579\",\"name\":\"巴中市方圆环保科技发展有限责任公司\"},{\"id\":\"3028329099\",\"name\":\"广元市昭化区华瑞投资开发有限公司\"},{\"id\":\"2351753474\",\"name\":\"四川川商返乡兴业股权投资基金中心（有限合伙）\"},{\"id\":\"2351975259\",\"name\":\"成都中车四方轨道车辆有限公司\"},{\"id\":\"1478418957\",\"name\":\"泸州兴园建设投资开发有限公司\"},{\"id\":\"160440622\",\"name\":\"四川有色新材料科技股份有限公司\"},{\"id\":\"1048295117\",\"name\":\"安岳县欣通建设投资有限公司\"},{\"id\":\"2390556629\",\"name\":\"四川省能投矿业投资开发有限公司\"},{\"id\":\"2328649289\",\"name\":\"四川蓬安工业园区投资开发管理有限责任公司\"},{\"id\":\"2328221202\",\"name\":\"巴中市鑫园创业融资担保有限公司\"},{\"id\":\"203411156\",\"name\":\"申万宏源集团股份有限公司\"},{\"id\":\"364822456\",\"name\":\"四川普什宁江机床有限公司\"},{\"id\":\"3240913802\",\"name\":\"四川省新能源动力股份有限公司\"},{\"id\":\"391697834\",\"name\":\"广元市园区建设投资有限公司\"},{\"id\":\"1035297230\",\"name\":\"广元市朝天区兴业融资担保有限公司\"},{\"id\":\"3288779338\",\"name\":\"国家军民融合产业投资基金有限责任公司\"},{\"id\":\"1115846739\",\"name\":\"广元市油气投资股份有限公司\"},{\"id\":\"2327109201\",\"name\":\"开江县金山投资经营有限责任公司\"},{\"id\":\"3297262646\",\"name\":\"四川省川南融资担保有限公司\"},{\"id\":\"166766277\",\"name\":\"四川虹视显示技术有限公司\"},{\"id\":\"167553680\",\"name\":\"大英县嘉泰城市建设投资开发有限责任公司\"},{\"id\":\"356565375\",\"name\":\"四川怡展实业有限公司\"},{\"id\":\"352717907\",\"name\":\"宜宾海丝特纤维有限责任公司\"},{\"id\":\"185082527\",\"name\":\"宜宾市翠屏区国有资产经营管理有限责任公司\"},{\"id\":\"3061071550\",\"name\":\"四川发展兴展产业引导股权投资基金合伙企业（有限合伙）\"},{\"id\":\"265570965\",\"name\":\"四川能投发展股份有限公司\"},{\"id\":\"3472171381\",\"name\":\"四川院士科技创新股权投资引导基金合伙企业（有限合伙）\"},{\"id\":\"140303492\",\"name\":\"四川九寨黄龙机场有限责任公司\"}]";
        //List<Company> companies = JsonUtils.readerList(companyStr, Company.class);
        List<Company> companies = queryCompany();
        System.out.println(JsonUtils.toString(companies));
        List<Map> jbos = new ArrayList<>();
        for(Company company : companies){
            List<Map> temp = search(company.getName());
            if(temp != null && temp.size() > 0){
                jbos.addAll(temp);
            }
        }
        TemplateExportParams params = new TemplateExportParams(
                "export_report_fund_template.xls");
        Map<String, Object> context = new HashMap<>();
        context.put("datas", jbos);
        Workbook workbook = ExcelExportUtil.exportExcel(params, context);
        try (FileOutputStream fos = new FileOutputStream("C:\\Users\\62772\\Desktop\\jobs\\" + System.currentTimeMillis() + ".xls")) {
            workbook.write(fos);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String uncompress(byte[] b) throws IOException {

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayInputStream in = new ByteArrayInputStream(b);
        GZIPInputStream gunzip = new GZIPInputStream(in);
        byte[] buffer = new byte[256];
        int n;
        while ((n = gunzip.read(buffer)) >= 0) {
            out.write(buffer, 0, n);
        }
        return new String(out.toByteArray(), "GBK");
    }

    public static List<Map> search(String companyName){
        try {
            String url = "https://search.51job.com/list/000000,000000,0000,00,9,99,"+ URLEncoder.encode(companyName, "UTF-8") +",1,1.html?lang=c&postchannel=0000&workyear=99&cotype=99&degreefrom=99&jobterm=99&companysize=99&ord_field=0&dibiaoid=0&line=&welfare=";
            HttpRequest request = new SimpleRequestBuilder().http(url);
            //request.header("Referer", "https://search.51job.com/list/000000,000000,0000,00,9,99,%25E6%2588%2590%25E9%2583%25BD%25E4%25BF%25A1%25E9%2580%259A%25E4%25BF%25A1%25E6%2581%25AF%25E6%258A%2580%25E6%259C%25AF%25E6%259C%2589%25E9%2599%2590%25E5%2585%25AC%25E5%258F%25B8,1,1.html?lang=c&postchannel=0000&workyear=99&cotype=99&degreefrom=99&jobterm=99&companysize=99&ord_field=0&dibiaoid=0&line=&welfare=");
            request.header("Cookie", "_uab_collina=164687655755004092296692; guid=682e56a1fb9a9b10c741eb08e844b631; slife=lowbrowser%3Dnot%26%7C%26; nsearch=jobarea%3D%26%7C%26ord_field%3D%26%7C%26recentSearch0%3D%26%7C%26recentSearch1%3D%26%7C%26recentSearch2%3D%26%7C%26recentSearch3%3D%26%7C%26recentSearch4%3D%26%7C%26collapse_expansion%3D; partner=sem_pcbaidubd_250; privacy=1647935863; acw_tc=2f624a3316479358653754319e141a9ad738917308b01b39c43e7b264e7102; acw_sc__v2=6239817c685ebd7895d9ed24fb4fb8bff1d7a25e; search=jobarea%7E%60000000%7C%21ord_field%7E%600%7C%21recentSearch0%7E%60000000%A1%FB%A1%FA000000%A1%FB%A1%FA0000%A1%FB%A1%FA00%A1%FB%A1%FA99%A1%FB%A1%FA%A1%FB%A1%FA99%A1%FB%A1%FA99%A1%FB%A1%FA99%A1%FB%A1%FA99%A1%FB%A1%FA9%A1%FB%A1%FA99%A1%FB%A1%FA%A1%FB%A1%FA0%A1%FB%A1%FA%B3%C9%B6%BC%D0%C5%CD%A8%D0%C5%CF%A2%BC%BC%CA%F5%D3%D0%CF%DE%B9%AB%CB%BE%A1%FB%A1%FA1%A1%FB%A1%FA1%7C%21recentSearch1%7E%60000000%A1%FB%A1%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99%A1%FB%A1%FA%A1%FB%A1%FA0%A1%FB%A1%FA%B3%C9%B6%BC%C8%D8%C5%B7%B9%A9%D3%A6%C1%B4%BC%AF%CD%C5%D3%D0%CF%DE%B9%AB%CB%BE%A1%FB%A1%FA2%A1%FB%A1%FA1%7C%21collapse_expansion%7E%601%7C%21; ssxmod_itna=iqmxgi0=F49D0Dl8D+obkwP7K5AIeDC7+iUDBwRd4iNDnD8x7YDv+G54pYzYlz4pBnX=HilYPimWWonivTYpWe0aDbqGkkYeoWeDxrq0rD74irDDxD3Db4dDSDWKD9D048yRvLKGWDbx=Di4D+iTQDmqG0DDtHj4G2D7tnl7w5ikiLtQU5skwxO4=DjdbD/RwbXCrTrZhMKlTIGhD4D0PzfPw8urPVtrQDzq7DtkUB0qL5L16lAuXYY7GT+t+1lRwW9G+rKBh=RY+6DEheeOM0Pox3W0kXji4dADDAKxSdeD; ssxmod_itna2=iqmxgi0=F49D0Dl8D+obkwP7K5AIeDC7+iD8umBOPGN33X=GaW=AHs7smy57x8OKP8DP3dei4RK+lyGp5dRTIxGzGIDBTIDkQ6OYA=XtjSNXMRzIFnGspULER1I5IKAZ9gLV/yCOfpHTueHbZ=uNpoa+DUBi7GHsgxbmMn0KSYqwl27G8texzmEsSZOwQRYbMiffI9fk==ejwtwC8fnLC63UwRMfNIcU=3lL3acXr6SQ5LgQxLgTNv36oM8Xdcip7N3HARdfSS8tYwmj3rrFYf7zOdAdFVHa3cgMPSUMV6xxcTcMndMwR9lDpARuKADVWx4uuDRrz4Pd/qQFBWKixvbq8HP1BWYGNzmQKiYQxDKLh+nPMG4NYehxK3gmpMrjnpzBCh7qD7=DY9qeD===");
            request.header("Accept-Encoding", "gzip, deflate");
            String result = uncompress(request.get().asBytes());
            int index = result.indexOf("window.__SEARCH_RESULT__ = ");
            int end = result.indexOf("\"seo_keywords\":\"找工作,求职,人才,招聘\"");
            if(index == -1 || end == -1){
                return new ArrayList<>();
            }
            result = result.substring(index + 27, end + 30);
            System.out.println(result);

            List<Map> engine_jds = (List<Map>)JsonUtils.reader(result, LinkedHashMap.class).get("engine_jds");
            List<Map> jobs = new ArrayList<>();
            for(Map map : engine_jds){
                String job_href = (String) map.get("job_href");
                String job_name = (String) map.get("job_name");
                String company_name = (String) map.get("company_name");
                String company_href = (String) map.get("company_href");
                String providesalary_text = (String) map.get("providesalary_text");
                String workarea_text = (String) map.get("workarea_text");
                String jobwelf = (String) map.get("jobwelf");
                jobs.add(new HashMap<String, Object>(){{
                    put("job_href", job_href);
                    put("job_name", job_name);
                    put("company_name", company_name);
                    put("company_href", company_href);
                    put("providesalary_text", providesalary_text);
                    put("workarea_text", workarea_text);
                    put("jobwelf", jobwelf);
                }});
            }
            return jobs;
        }catch (Exception e){
            throw new RuntimeException("", e);
        }

    }


    public static List<Company> queryCompany()  {
        try {
            //List<Company> companies = querySubCompany("155872807");
            List<Company> companies = querySubCompany("3145468925");
            List<Company> result = new ArrayList<>();
            for (Company company : companies) {
                List<Company> temp1 = querySubCompany(company.getId());
                result.containsAll(temp1);
                for (Company company1 : temp1) {
                    List<Company> temp2 = querySubCompany(company1.getId());
                    result.containsAll(temp2);
                    for (Company company2 : temp2) {
                        List<Company> temp3 = querySubCompany(company2.getId());
                        result.containsAll(temp3);
                        for (Company company3 : temp3) {
                            List<Company> temp4 = querySubCompany(company3.getId());
                            result.containsAll(temp4);
                        }
                    }
                }
            }
            result.addAll(companies);
            return companies;
        }catch (Exception e){
            throw new RuntimeException("", e);
        }
    }

    private static List<Company> querySubCompany(String id) throws Exception {
        List<Company> companies = new ArrayList<>();
        try {
            HttpRequest request =  new SimpleRequestBuilder().http("https://capi.tianyancha.com/cloud-company-background/company/enterpriseMap?gid=" + id);
            request.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36" + new Random().nextInt(1000));
            //request.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36" + new Random().nextInt(1000));
            String companys = request.get().asString();
            List<Map> inversts = (List<Map>) ((Map) JsonUtils.reader(companys, LinkedHashMap.class).get("data")).get("inverst");
            if (inversts == null || inversts.size() == 0) {
                return Collections.emptyList();
            }
            inversts.forEach(row -> {
                companies.add(Company.builder().id(row.get("id").toString()).name(row.get("name").toString()).build());
            });
        }catch (Exception e){
            e.printStackTrace();
        }
        return companies;
    }

    @AllArgsConstructor
    @Data
    @NoArgsConstructor
    @Builder
    public static class Company {
        private String id;
        private String name;
    }
}
